//
//  RegisterViewController.m
//  atXiaoGeBClient
//
//  Created by Linyu Niu on 12/04/2018.
//  Copyright © 2018 Linyu Niu. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSString * phoneNumber;
    NSString * codeNumber;
    NSString * pwd;
    NSInteger time;
    NSTimer * timer;
    NSCache * cellCache;
    UITableView * registerTable;
}
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    cellCache = [[NSCache alloc]init];
    __weak RegisterViewController * weakSelf = self;
    UIView * navView = [[CTMediator sharedInstance] navgationHeadViewInTargetView:self.view params:[NSDictionary dictionaryWithObjectsAndKeys:@"成为艾特小哥",@"title", nil] leftAction:^(UIButton * sender){
        [weakSelf stopTimer];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } rightAction:nil];
   registerTable =  [self addTableViewInView:self.view frame:CGRectMake(0, navView.frame.origin.y + navView.frame.size.height + 30, self.view.frame.size.width, self.view.frame.size.height - navView.frame.size.height - navView.frame.origin.y) delegateAndDataSource:self];
}

-(void)stopTimer{
    UIButton * button = timer.userInfo;
    button.enabled = YES;
    [button setTitle:@"发送验证码" forState:UIControlStateNormal];
    [timer invalidate];
    timer = nil;
    
    
}

-(void)startTimer:(UIButton *)sender{
    sender.enabled = NO;
    if (!timer) {
        time = 60;
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setButtonTitle:) userInfo:sender repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }
}

-(void)setButtonTitle:(NSTimer *)t{
//    NSLog(@"setButtonTitle----setButtonTitle-----%d",time);
    UIButton * button = (UIButton *)t.userInfo;
    if (time > 0) {
        time -- ;
        
        [button setTitle:[NSString stringWithFormat:@"%@秒后重新获取",[NSNumber numberWithInteger:time]] forState:UIControlStateNormal];
    }else{
        [self stopTimer];
        [button setTitle:@"发送验证码" forState:UIControlStateNormal];
    }
}
-(void)completeRegister{
    [self.view endEditing:YES];
    
    
    if (phoneNumber && codeNumber && pwd) {
        [self startLoadingView:self.view];
        
        __weak RegisterViewController * weakSelf = self;
        [[CTMediator sharedInstance] registerOrLogin:phoneNumber code:codeNumber pwd:pwd block:^(NSDictionary * result){
            if ([weakSelf stopLoadingView:self.view needShowMsg:YES result:result]) {
                UIViewController * controller = [[CTMediator sharedInstance] completeRegisterController:[result objectForKey:@"courierId"]];
                [weakSelf.navigationController pushViewController:controller animated:YES];
            }
        }];
    }
}
-(void)sendCode:(UIButton *)sender{
    [self.view endEditing:YES];
    if (phoneNumber) {
        [self startLoadingView:self.view];
        [self startTimer:sender];
        __weak RegisterViewController * weakSelf = self;
        [[CTMediator sharedInstance] getTokenWithTokentype:[NSNumber numberWithInteger:1].stringValue block:^(NSDictionary * result){
            NSString * token = [result objectForKey:@"token"];
            if (token) {
                [[CTMediator sharedInstance] setToken:token];
                [[CTMediator sharedInstance] sendMessageWithType:@"1" mobile:phoneNumber block:^(NSDictionary * smsResult){
#if kDevelopment
//                    codeNumber = [smsResult objectForKey:@"valiCode"];
//                    [registerTable reloadData];
#endif
                    [weakSelf stopLoadingView:weakSelf.view needShowMsg:YES result:smsResult];
                    if (![self isSuccess:smsResult]) {
                        [weakSelf stopTimer];
                    }
                }];
            }else{
                [weakSelf stopTimer];
                [weakSelf stopLoadingView:weakSelf.view needShowMsg:YES result:result];
            }
        }];
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ElementTableViewCell * cell = [cellCache objectForKey:indexPath];
    if (!cell) {
        cell = [[ElementTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        NSInteger xSpace = 30;
        
        if ([indexPath row] < 3) {
            UITextField * field = [[UITextField alloc]initWithFrame:CGRectMake(xSpace, 10, tableView.frame.size.width - 2 * xSpace, 25)];
            field.delegate = self;
            field.tag = [indexPath row];
            field.font = [UIFont systemFontOfSize:14];
            field.keyboardType = UIKeyboardTypeNumberPad;
            field.textColor = [UIColor colorWithRed:64.0 / 255.0 green:78.0 / 255.0 blue:89.0 / 255.0 alpha:1.0];
            [cell addSubview:field];
            if ([indexPath row] == 0) {
                UILabel * nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 5, 40, 25)];
                nameLabel.font = [UIFont systemFontOfSize:14];
                nameLabel.text = @"+86";
                [nameLabel enlargeWidthToKeepFontSize];
                [cell addSubview:nameLabel];
                field.placeholder = @"请输入手机号码";
                field.text = phoneNumber;
                UIView * vLine = [[UIView alloc]initWithFrame:CGRectMake(nameLabel.frame.origin.x + nameLabel.frame.size.width + 4, nameLabel.frame.origin.y + 3, 0.5, nameLabel.frame.size.height - 6)];
                vLine.backgroundColor = [UIColor colorWithRed:228.0 / 255.0 green:228.0 / 255.0 blue:228.0 / 255.0 alpha:1.0];
                [cell addSubview:vLine];
                
                field.frame = CGRectMake(vLine.frame.origin.x + vLine.frame.size.width + 5, vLine.frame.origin.y, tableView.frame.size.width - vLine.frame.origin.x - xSpace, vLine.frame.size.height);
            }else if([indexPath row] == 1){
                field.placeholder = @"请输入验证码";
                field.text = codeNumber;
                UIButton * sendCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
                sendCodeButton.frame = CGRectMake(tableView.frame.size.width - xSpace - 135, field.frame.origin.y, 135, field.frame.size.height);
                sendCodeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
                [sendCodeButton setTitleColor:[UIColor colorWithRed:64.0 / 255.0 green:198.0 / 255.0 blue:124.0 / 255.0 alpha:1.0] forState:UIControlStateNormal];
                sendCodeButton.titleLabel.font = [UIFont systemFontOfSize:14];
                [sendCodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
                [sendCodeButton addTarget:self action:@selector(sendCode:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:sendCodeButton];
                
                field.frame = CGRectMake(field.frame.origin.x, field.frame.origin.y, tableView.frame.size.width - xSpace * 2 - sendCodeButton.frame.size.width - 5, field.frame.size.height);
            }else if([indexPath row] == 2){
                field.placeholder = @"请设置登录密码";
                field.keyboardType = UIKeyboardTypeDefault;
                field.secureTextEntry = YES;
                field.text = pwd;
            }
            cell.cellHeight = field.frame.size.height + field.frame.origin.y + 10;
        }else if([indexPath row] == 3){
            NSString * serviceString = @"完成注册表示您已同意《艾特小哥服务协议》";
            
            
            UILabel *serviceLabel = [[UILabel alloc] init];
            serviceLabel.text = serviceString;
            serviceLabel.textAlignment = NSTextAlignmentCenter;
            
            serviceLabel.font = [UIFont systemFontOfSize:12];
            serviceLabel.frame = CGRectMake(0, 20, tableView.frame.size.width, 20);
            serviceLabel.textColor = [UIColor colorWithRed:102.0 / 255.0 green:102.0 / 255.0 blue:102.0 / 255.0 alpha:1.0];
            serviceLabel.backgroundColor = [UIColor clearColor];
            [cell addSubview:serviceLabel];
            cell.cellHeight = serviceLabel.frame.size.height + serviceLabel.frame.origin.y * 2;
        }else if([indexPath row] == 4){
            UIButton * registerButton = [[CTMediator sharedInstance] commonOrangeButton:CGRectMake(xSpace, 10, tableView.frame.size.width - 2 * xSpace, 35) title:@"提交" delegate:self action:@selector(completeRegister)];
            [cell addSubview:registerButton];
            cell.cellHeight = registerButton.frame.size.height + registerButton.frame.origin.y * 2;
        }
        
        
        if ([indexPath row] < 3) {
            UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(xSpace, cell.cellHeight - 1.0, tableView.frame.size.width - 2 * xSpace, 1.0)];
            lineView.backgroundColor = [UIColor colorWithRed:228.0 / 255.0 green:228.0 / 255.0 blue:228.0 / 255.0 alpha:1.0];
            [cell addSubview:lineView];
        }
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ElementTableViewCell * cell = (ElementTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}


-(void)textFieldDidEndEditing:(UITextField *)textField{
    if(textField.text.length != 0){
        if (textField.tag == 0) {
            phoneNumber = textField.text;
        }else if(textField.tag == 1){
            codeNumber = textField.text;
        }else if(textField.tag == 2){
            pwd = textField.text;
        }
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 0) {
        if ([string isEqualToString:@""] || [string isEqualToString:@"\n"]) {
            
            return YES;
        }else{
            if (textField.text.length == 3 || textField.text.length == 8) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
            
            NSString * numString = [NSString stringWithFormat:@"%@%@",textField.text,string];
            
            if ([numString length] == 14) {
                
                return NO;
            }
        }
    }
    
    
    return YES;
}


-(void)dealloc{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}
@end
